package com.suray.attendance.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.suray.attendance.connect.ErpApiConnectByServerRequestProd;
import com.suray.attendance.model.bean.DocInfoParameter;
import com.suray.attendance.model.enums.erp.ErpApiServerNameEnum;
import com.suray.attendance.connect.ErpApiConnect;
import com.suray.attendance.service.ErpService;
import com.suray.attendance.common.utils.LoggerUtil;
import com.suray.attendance.model.bean.Execution;
import com.suray.attendance.model.bean.DocInfoStdData;
import com.suray.attendance.model.enums.erp.DingwinMethod;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@CommonsLog
public class ErpServiceImpl implements ErpService {

	private ErpApiConnectByServerRequestProd erpApiConnectByServerRequestProd = new ErpApiConnectByServerRequestProd();

	@Value("${dingwin.restUrl}")
	String restUrl;


	@Override
	public Map<String,Object> add(String docType, String jsonData,String requestProd) {
		ErpApiServerNameEnum serverNameAndClassType = ErpApiServerNameEnum.getServerNameAndClassTypeByDocTypeName(docType);
		String serverName = DingwinMethod.创建.getServerName(serverNameAndClassType.getServerName());
		try {
//	TODO		JSONObject re = ErpApiConnect.create(restUrl,serverName,jsonData);
			JSONObject re = erpApiConnectByServerRequestProd.create(restUrl,serverName,jsonData,requestProd);
			DocInfoStdData data = JSONObject.parseObject(re.getJSONObject("std_data").toJSONString(), DocInfoStdData.class);
			String code = data.getExecution().getCode();
			List<Map<String, Object>> error = data.getParameter().getResult().getError();
			if(Execution.成功.equals(code) && error == null) {
				List<Map<String, Object>> success = data.getParameter().getResult().getSuccess();
				return success.get(0);
			}else{
				LoggerUtil.error(docType+"创建erp工单异常"+error.get(0).get("message"),ErpServiceImpl.class);
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			LoggerUtil.error(docType+"创建erp工单异常，异常信息为"+e.getMessage(),ErpServiceImpl.class);
			return null;
		}
	}

	/**
	 * @param docType
	 * @param docNo
	 * @Description: 根据工单单获取工单数据
	 * @Param: [docType, docNo]
	 * @Author: jly
	 * @Date: 2023/11/13
	 * @return
	 */
	@Override
	public Object read(String docType, String docNo,String requestProd) {
		ErpApiServerNameEnum serverNameAndClassType = ErpApiServerNameEnum.getServerNameAndClassTypeByDocTypeName(docType);
		String serverName = DingwinMethod.读取.getServerName(serverNameAndClassType.getServerName());
		Class classType = serverNameAndClassType.getClassType();
		List<String[]> readMaps = new ArrayList<String[]>();
		readMaps.add(new String[]{docNo});
		try {
//	TODO		JSONObject re = ErpApiConnect.readOrUpdateApproveStatus(restUrl,serverName,readMaps);
			JSONObject re = erpApiConnectByServerRequestProd.readOrUpdateApproveStatus(restUrl,serverName,readMaps,requestProd);
			DocInfoStdData data = JSONObject.parseObject(re.getJSONObject("std_data").toJSONString(), DocInfoStdData.class);
			String code = data.getExecution().getCode();
			List<Map<String, Object>> error = data.getParameter().getResult().getError();
			if(Execution.成功.equals(code) && error == null) {
				// 根据单据类型获取需要解析的list数据
				List<Map<String,Object>> rows = data.getParameter().getResult().getSuccess();
				JSONObject fromHashMap = (JSONObject) JSON.toJSON(rows.get(0));
				LoggerUtil.info(docNo+docType+"鼎捷erp读取成功",ErpServiceImpl.class);
				return JSON.toJavaObject(fromHashMap, classType);
			}else {
				LoggerUtil.error(docNo+docType+"鼎捷erp读取异常"+error.get(0).get("message"),ErpServiceImpl.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
			LoggerUtil.error(docNo+docType+"鼎捷erp读取异常"+e.getMessage(),ErpServiceImpl.class);
		}
		return null;
	}


	/**
	 * @description: 查询未审核的请购单信息
	 * @author: jianglinyu
	 * @date: 2023/7/13 9:48
	 * {
	 *   "std_data": {
	 *     "parameter": {
	 *       "page_size": 20,
	 *       "page_no": 1,
	 *       "is_get_schema": false,
	 *       "is_get_count": false,
	 *       "conditions": [{"field_name":"project_no",
	 * 						 "value":"RD-DLKZB-20230101",
	 * 						 "operator":"="}],
	 *       "orders":[{"field_name":"doc_no","order_type":"desc"}]
	 *     }
	 *   }
	 * }
	 **/
	@Override
	public List<Object> query(String docType,String requestProd) {
		ErpApiServerNameEnum serverNameAndClassType = ErpApiServerNameEnum.getServerNameAndClassTypeByDocTypeName(docType);
		String serverName = DingwinMethod.查询.getServerName(serverNameAndClassType.getServerName());
		Class classType = serverNameAndClassType.getClassType();
		List<String[]> queryMaps = new ArrayList<String[]>();
		queryMaps.add(new String[]{"project_no","RD-DLKZB-20230101","="});
		queryMaps.add(new String[]{"doc_type_no","5136","="});
		List<String[]> orderMaps = new ArrayList<String[]>();
		orderMaps.add(new String[]{"doc_no", "desc"});
		try {
			List<Object> response = new ArrayList<>();
			Integer pageNo=1;
			Integer totalNumber = null;
			Double pageNumber = null;
			do {
//	TODO			JSONObject re = ErpApiConnect.query(restUrl,serverName,queryMaps, orderMaps,pageNo);
				JSONObject re = erpApiConnectByServerRequestProd.query(restUrl,serverName,queryMaps, orderMaps,pageNo,requestProd);
				DocInfoStdData data = JSONObject.parseObject(re.getJSONObject("std_data").toJSONString(), DocInfoStdData.class);
				String code = data.getExecution().getCode();
				if(Execution.成功.equals(code)) {
					// 根据单据类型获取需要解析的list数据
					DocInfoParameter parameter = data.getParameter();
					List<Map<String,Object>> rows = parameter.getRows();
					totalNumber = parameter.getCnt();
					pageNumber = (totalNumber!=null && totalNumber!=0)?totalNumber/5000.0:1.0;
					List<Object> queryResult = rows.stream().map(entity -> {
						JSONObject fromHashMap = (JSONObject) JSON.toJSON(entity);
						Object o = JSON.toJavaObject(fromHashMap, classType);
						return classType.cast(o);
					}).collect(Collectors.toList());
					LoggerUtil.info(docType+"鼎捷erp查询成功",ErpServiceImpl.class);
					response.addAll(queryResult);
				}else{
					LoggerUtil.error("查询鼎捷erp中"+docType+"异常",ErpServiceImpl.class);
				}
			}while (pageNo++<pageNumber);
			return response;
		} catch (Exception e) {
			e.printStackTrace();
			LoggerUtil.error("查询鼎捷erp中"+docType+"异常"+e.getMessage(),ErpServiceImpl.class);
			return null;
		}
	}

	/**
	 * @description: 根据条件查询信息
	 * @author: jly
	 * @date: 2023/11/14 16:05
	 **/
	@Override
	public List<Object> queryCondition(String docType, List<String[]> queryMaps, List<String[]> orderMaps,String requestProd) {
//	public List<Object> queryCondition(String docType,String fieldName,String fieldValue,String operator,String orderFieldName,String rule) {
		ErpApiServerNameEnum serverNameAndClassType = ErpApiServerNameEnum.getServerNameAndClassTypeByDocTypeName(docType);
		String serverName = DingwinMethod.查询.getServerName(serverNameAndClassType.getServerName());
		if("考勤报工收集单".equals(docType)){
			serverName = serverNameAndClassType.getServerName();
		}
		Class classType = serverNameAndClassType.getClassType();
//		List<String[]> queryMaps = new ArrayList<String[]>();
//		queryMaps.add(new String[]{fieldName,fieldValue,operator});
////		queryMaps.add(new String[]{"DOC_NO","3140-23070022","="});
////		queryMaps.add(new String[]{"APPROVESTATUS","N","="});
//		List<String[]> orderMaps = new ArrayList<String[]>();
////		orderMaps.add(new String[]{"DOC_NO", "desc"});
//		orderMaps.add(new String[]{orderFieldName, rule});
		try {
			List<Object> response = new ArrayList<>();
			Integer pageNo=1;
			Integer totalNumber = null;
			Double pageNumber = null;
			do {
//	TODO			JSONObject re = ErpApiConnect.query(restUrl,serverName,queryMaps, orderMaps,pageNo);
				JSONObject re = erpApiConnectByServerRequestProd.query(restUrl,serverName,queryMaps, orderMaps,pageNo,requestProd);
				DocInfoStdData data = JSONObject.parseObject(re.getJSONObject("std_data").toJSONString(), DocInfoStdData.class);
				String code = data.getExecution().getCode();
				if(Execution.成功.equals(code)) {
					// 根据单据类型获取需要解析的list数据
					DocInfoParameter parameter = data.getParameter();
					List<Map<String,Object>> rows = parameter.getRows();
					totalNumber = parameter.getCnt();
					pageNumber = (totalNumber!=null && totalNumber!=0)?totalNumber/5000.0:1.0;
					List<Object> queryResult = rows.stream().map(entity -> {
						JSONObject fromHashMap = (JSONObject) JSON.toJSON(entity);
						Object o = JSON.toJavaObject(fromHashMap, classType);
						return classType.cast(o);
					}).collect(Collectors.toList());
					LoggerUtil.info(docType+"自定义条件查询鼎捷erp查询成功",ErpServiceImpl.class);
					response.addAll(queryResult);
				}else{
					LoggerUtil.error("自定义条件查询鼎捷erp"+docType+"异常",ErpServiceImpl.class);
				}
			}while (pageNo++<pageNumber);
			return response;
		} catch (Exception e) {
			e.printStackTrace();
			LoggerUtil.error("自定义条件查询鼎捷erp"+docType+"异常"+e.getMessage(),ErpServiceImpl.class);
			return null;
		}
	}

	/**
	 * @description:  审核单条数据
	 * @author:  jly
	 * @date: 2023/11/14 10:40
	 * @return*/
	@Override
	public Boolean approve(String docType, String docNo,String requestProd) {
		ErpApiServerNameEnum serverNameAndClassType = ErpApiServerNameEnum.getServerNameAndClassTypeByDocTypeName(docType);
		String serverName = DingwinMethod.审核.getServerName(serverNameAndClassType.getServerName());
		List<String[]> readMaps = new ArrayList<String[]>();
		readMaps.add(new String[]{docNo});
		try {
//	TODO		JSONObject re = ErpApiConnect.readOrUpdateApproveStatus(restUrl,serverName,readMaps);
			JSONObject re = erpApiConnectByServerRequestProd.readOrUpdateApproveStatus(restUrl,serverName,readMaps,requestProd);
			DocInfoStdData data = JSONObject.parseObject(re.getJSONObject("std_data").toJSONString(), DocInfoStdData.class);
			String code = data.getExecution().getCode();
			List<Map<String, Object>> error = data.getParameter().getResult().getError();
			if(Execution.成功.equals(code) && error == null) {
				LoggerUtil.info(docNo+docType+"鼎捷erp审核成功，"+data.getExecution().getDescription(),ErpServiceImpl.class);
				return true;
			}
			else{
				LoggerUtil.error(docNo+docType+"鼎捷erp审核异常，"+data.getExecution().getDescription()+"接口执行成功，但是系统限制异常"+Arrays.asList(error),ErpServiceImpl.class);
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			LoggerUtil.error(docNo+docType+"鼎捷erp审核异常，"+e.getMessage(),ErpServiceImpl.class);
			return false;
		}
	}

	/**
	 * @description: 作废单条数据
	 * @author: jly
	 * @date: 2023/11/14 10:40
	 */
	@Override
	public Boolean invalid(String docType, String docNo,String requestProd) {
		ErpApiServerNameEnum serverNameAndClassType = ErpApiServerNameEnum.getServerNameAndClassTypeByDocTypeName(docType);
		String serverName = DingwinMethod.作废.getServerName(serverNameAndClassType.getServerName());
		List<String[]> readMaps = new ArrayList<String[]>();
		readMaps.add(new String[]{docNo});
		try {
//			JSONObject re = ErpApiConnect.readOrUpdateApproveStatus(restUrl,serverName,readMaps);
			JSONObject re = erpApiConnectByServerRequestProd.readOrUpdateApproveStatus(restUrl,serverName,readMaps,requestProd);
			DocInfoStdData data = JSONObject.parseObject(re.getJSONObject("std_data").toJSONString(), DocInfoStdData.class);
			String code = data.getExecution().getCode();
			List<Map<String, Object>> error = data.getParameter().getResult().getError();
			if(Execution.成功.equals(code) && error == null) {
				LoggerUtil.info(docNo+docType+"鼎捷erp作废成功，"+data.getExecution().getDescription(),ErpServiceImpl.class);
				return true;
			}
			else{
				LoggerUtil.error(docNo+docType+"鼎捷erp作废异常，"+data.getExecution().getDescription(),ErpServiceImpl.class);
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			LoggerUtil.error(docNo+docType+"鼎捷erp作废异常，"+e.getMessage(),ErpServiceImpl.class);
			return false;
		}
	}

	/**
	 * @description: 撤销审核单条数据
	 * @author: jly
	 * @date: 2023/11/14 10:40
	 */
	@Override
	public Boolean disapprove(String docType, String docNo,String requestProd) {
		ErpApiServerNameEnum serverNameAndClassType = ErpApiServerNameEnum.getServerNameAndClassTypeByDocTypeName(docType);
		String serverName = DingwinMethod.撤销审核.getServerName(serverNameAndClassType.getServerName());
		List<String[]> readMaps = new ArrayList<String[]>();
		readMaps.add(new String[]{docNo});
		try {
//	TODO		JSONObject re = ErpApiConnect.readOrUpdateApproveStatus(restUrl,serverName,readMaps);
			JSONObject re = erpApiConnectByServerRequestProd.readOrUpdateApproveStatus(restUrl,serverName,readMaps,requestProd);
			DocInfoStdData data = JSONObject.parseObject(re.getJSONObject("std_data").toJSONString(), DocInfoStdData.class);
			String code = data.getExecution().getCode();
			List<Map<String, Object>> error = data.getParameter().getResult().getError();
			if(Execution.成功.equals(code) && error == null) {
				LoggerUtil.info(docNo+docType+"鼎捷erp撤销审核成功，"+data.getExecution().getDescription(),ErpServiceImpl.class);
				return true;
			}
			else{
				LoggerUtil.error(docNo+docType+"鼎捷erp撤销审核异常，"+data.getExecution().getDescription(),ErpServiceImpl.class);
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			LoggerUtil.error(docNo+docType+"鼎捷erp撤销审核异常，"+e.getMessage(),ErpServiceImpl.class);
			return false;
		}
	}

}
